package common;

import java.util.Iterator;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.RootClass;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;

public class HibernateUtil {

	public static SessionFactory sessionFactory;

	static {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			sessionFactory = new Configuration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

	public static Session getCurrentSession() throws HibernateException {
		Session s = session.get();
		// Open a new Session, if this thread has none yet
		if (s == null) {
			s = sessionFactory.openSession();
			// Store it in the ThreadLocal variable
			session.set(s);
		}
		return s;
	}

	public static void closeSession() throws HibernateException {
		Session s = (Session) session.get();
		if (s != null)
			s.close();
		session.set(null);
	}
//	public static boolean setTableName(String strBefore, String strAfter){
//		return true;
//	}
//	static {
	public static void setTableName(String strBefore, String strAfter){
        Configuration configuration; 
        try{ 
          configuration = new Configuration().configure("/hibernate.cfg.xml"); 
            Iterator iterator = configuration.getClassMappings();
            while (iterator.hasNext()) {              
              RootClass rootClass = (RootClass)iterator.next(); 
//              if (rootClass.getTable().getName().equals("zipcode")){ 
//            	  rootClass.getTable().setName("CSeoul");
              if (rootClass.getTable().getName().equals(strBefore)){ 
            	  rootClass.getTable().setName(strAfter);
            	  System.out.println("Before : " + strBefore + " After : " + strAfter);
                  
            	 setSessionFactory(configuration.buildSessionFactory()); 

            	 new SchemaExport(configuration).create(false,false);
              } 
            } 
        } 
        catch(Throwable ex){ 
          throw new ExceptionInInitializerError(ex);          
        }
        // Print generated schema to console
        new SchemaExport(configuration).create(false,false);
    }

    public static synchronized Session getSession() {
        if (sessionFactory == null) {
        	sessionFactory = new Configuration().configure().buildSessionFactory();
        }
        return sessionFactory.openSession();
    }

    public static void setSessionFactory(SessionFactory factory) {
        HibernateUtil.sessionFactory = factory;
    }
}